package com.jh.discovery.zk.client.controller;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.context.event.EventListener;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
public class RemoteAppEventReceiverController implements ApplicationEventPublisherAware {

    private ApplicationEventPublisher publisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }

    @PostMapping("/receive/remote/event")
    public String receive(@RequestBody Map<String, Object> data) {

        // 事件发送者
        String sender = (String) data.get("sender");
        // 事件的数据内容
        Object value = data.get("value");
        // 事件类型
        String type = (String) data.get("type");

        SenderRemoteAppEvent event = new SenderRemoteAppEvent(value, sender);
        publisher.publishEvent(event);

        return "receive";

    }

    private static class SenderRemoteAppEvent extends ApplicationEvent {

        private String sender;

        /**
         * Create a new ApplicationEvent.
         *
         * @param source the object on which the event initially occurred (never {@code null})
         * @param sender
         */
        public SenderRemoteAppEvent(Object source, String sender) {
            super(source);
            this.sender = sender;
        }

        public String getSender() {
            return sender;
        }
    }

    @EventListener
    public void onMessage(SenderRemoteAppEvent event) {
        System.out.println("接收到事件源：" + event.getSource() + " ，来自应用：" + event.getSender());
    }

}
